<template>
  <div class="app-container">
    <upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload" />
    <el-table :data="tableData" border highlight-current-row style="width: 100%;margin-top:20px;">
      <el-table-column v-for="item of tableHeader" :key="item" :prop="item" :label="item" />
    </el-table>
  </div>
</template>

<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { formatExcelDate } from '@/utils/index'
import { importEmployees } from '@/api/employees'

export default {
  name: 'UploadExcel',
  components: { UploadExcelComponent },
  data() {
    return {
      tableData: [],
      tableHeader: []
    }
  },
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    // 文件上传成功后触发的函数
    handleSuccess({ results, header }) {
      this.tableData = results
      this.tableHeader = header
      const data = this.dataFormat(results)
      this.doAdd(data)
      this.$router.back()
      console.log(data, 'data')
    },
    // 将中文属性名转换为英文属性名
    dataFormat(data) {
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
      const result = data.map(item => {
        const obj = {}
        const zhKeys = Object.keys(item)
        // console.log(zhKeys)
        zhKeys.map(one => {
          const enKeys = mapInfo[one]
          if (enKeys === 'timeOfEntry' || enKeys === 'correctionTime') {
            obj[enKeys] = formatExcelDate(item[one])
          } else {
            obj[enKeys] = item[one]
          }
        })
        return obj
      })
      return result
    },
    // 批量导入员工信息
    async doAdd(data) {
      try {
        const res = await importEmployees(data)
        console.log(res)
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>
